// static/js/schedule_mgmt.js
;(function () {
    const form = document.getElementById('schedule-form');
    const typeSel = document.getElementById('schedType');
    const oneGr = document.getElementById('oneDateGroup');
    const weekGr = document.getElementById('weeklyDays');
    const startGr = document.getElementById('startDateGroup');
    const endGr = document.getElementById('endDateGroup');
    const errElFooter = document.getElementById('scheduleErrorFooter');


    async function loadMeta() {
        const [cs, ss, gs] = await Promise.all([
            fetch('/api/courses').then(r => r.json()),
            fetch('/api/schools').then(r => r.json()),
            fetch('/api/grades').then(r => r.json())
        ]);
        const csel = document.getElementById('schedCourse');
        cs.forEach(c => csel.add(new Option(c.name, c.name)));
        const ssel = document.getElementById('schedSchool');
        ss.forEach(s => ssel.add(new Option(s.name, s.name)));
        const gsel = document.getElementById('schedGrade');
        gs.forEach(g => gsel.add(new Option(g.name, g.name)));
    }

    // 切换类型时显示/隐藏相关字段
    typeSel.addEventListener('change', () => {
        if (typeSel.value === 'once') {
            oneGr.classList.remove('d-none');
            weekGr.classList.add('d-none');
            startGr.classList.add('d-none');
            endGr.classList.add('d-none');
        } else {
            oneGr.classList.add('d-none');
            weekGr.classList.remove('d-none');
            startGr.classList.remove('d-none');
            endGr.classList.remove('d-none');
        }
    });

    // 打开 Modal 时重置
    document.getElementById('scheduleModal')
        .addEventListener('show.bs.modal', () => {
            // 每次打开前先清空旧的下拉选项（保留第一个提示项）
            const csel = document.getElementById('schedCourse');
            csel.innerHTML = '<option value="" disabled selected>请选择课程</option>';
            const ssel = document.getElementById('schedSchool');
            ssel.innerHTML = '<option value="" disabled selected>请选择学校</option>';
            const gsel = document.getElementById('schedGrade');
            gsel.innerHTML = '<option value="" disabled selected>请选择年级</option>';

            loadMeta();       // 再重新拉取并填充
            form.reset();
            errElFooter.style.display = 'none';
            typeSel.value = 'once';
            typeSel.dispatchEvent(new Event('change'));
        });

    // 提交表单
    form.addEventListener('submit', async e => {
        e.preventDefault();
        errElFooter.style.display = 'none';
        const data = Object.fromEntries(new FormData(form).entries());
        // 处理多选星期
        if (data.type === 'weekly') {
            data.weekdays = Array.from(
                document.querySelectorAll('#weeklyDays .btn-check:checked')
            ).map(cb => cb.value);
        }
        try {
            const res = await fetch('/api/schedules', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify(data)
            });
            const text = await res.text();
            const payload = JSON.parse(text);
            if (!res.ok) throw new Error(payload.error || payload.message || text);
            // 成功
            form.closest('.modal').querySelector('[data-bs-dismiss="modal"]').click();
            if (typeof loadCards === 'function') loadCards();
            // TODO: 刷新日程卡片
        } catch (err) {
            errElFooter.textContent = err.message;
            errElFooter.style.display = 'inline';
            setTimeout(() => errElFooter.style.display = 'none', 3000);
        }
    });
})();
